package com.cxs.qrcode.slice;

import com.cxs.qrcode.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.ai.cv.common.ConnectionCallback;
import ohos.ai.cv.common.VisionManager;
import ohos.ai.cv.qrcode.IBarcodeDetector;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;


public class MainAbilitySlice extends AbilitySlice {
    private Text textInfo;
    private boolean isConnect = false;
    private Image imageQR;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        imageQR = (Image) findComponentById(ResourceTable.Id_qr_image);
        // 连接能力引擎
        int init = VisionManager.init(MainAbilitySlice.this, connectionCallback);

        findComponentById(ResourceTable.Id_btn_create_qr).setClickedListener(c -> {
            if (isConnect) {
                createQR();
            }
        });
    }

    private void createQR() {
        final int QR_LENGTH = 400;
        // 定义码生成图像的尺寸，并根据图像大小分配字节流数组空间。
        byte[] bytes = new byte[QR_LENGTH * QR_LENGTH * 4];
        // 实例化IBarcodeDetector接口
        IBarcodeDetector barcodeDetector = VisionManager.getBarcodeDetector(MainAbilitySlice.this);
        // 调用IBarcodeDetector的detect()方法，根据输入的字符串信息生成相应的二维码图片字节流。如果返回值为0，表明调用成功。
        int detect = barcodeDetector.detect("hello!你好啊！", bytes, QR_LENGTH, QR_LENGTH);
        if (detect == 0) {
            // 从字节流 bytes 创建图像数据源 ImageSource
            ImageSource imageSource = ImageSource.create(bytes, null);
            // 解码原始图像
            PixelMap pixelmap = imageSource.createPixelmap(null);
            imageQR.setPixelMap(pixelmap);
            // 释放码生成能力
            int release = barcodeDetector.release();
            // 断开与能力引擎的连接
            VisionManager.destroy();
        }
    }
    // 定义ConnectionCallback回调，实现连接能力引擎成功与否后的操作
    ConnectionCallback connectionCallback = new ConnectionCallback() {
        @Override
        public void onServiceConnect() {
            isConnect = true;
        }

        @Override
        public void onServiceDisconnect() {
            isConnect = false;
        }
    };
    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
